import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:playtruly/common/routers/names.dart';
import 'package:playtruly/common/services/user_service.dart';
import 'package:playtruly/common/services/rongcloud_service.dart';
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/api/friend_api.dart';
import 'package:playtruly/common/api/activity_api.dart';
import 'package:playtruly/common/api/user_api.dart';
import 'package:playtruly/pages/message/message_chat/controller.dart';
import 'package:playtruly/pages/my/my_index/controller.dart';
import 'package:playtruly/common/utils/toast_util.dart';
import 'package:playtruly/common/utils/permission_util.dart'; // 🎯 权限计算工具
import 'dart:developer' as developer;

class UserInfoController extends GetxController {
  // 用户服务
  final UserService userService = UserService.to;
  
  // 当前展示的用户（可以是传入的其他用户或当前登录用户）
  ChatUser? otherUser;
  
  // 从API获取的其他用户详细信息
  Map<String, dynamic>? otherUserDetails;
  
  // 当前用户信息（响应式）
  UserData? get currentUser => userService.currentUser;
  
  // 轮播图URL列表
  final RxList<String> carouselImages = <String>[].obs;
  
  // 当前轮播图索引
  final RxInt currentCarouselIndex = 0.obs;
  
  // 是否已添加为好友
  final RxBool isFriend = false.obs;
  
  // 是否显示当前登录用户（true=显示当前用户，false=显示其他用户）
  final RxBool isCurrentUser = true.obs;
  
  // 🔥 新增：当前用户的活动数据
  final RxList<ActivityData> _currentUserActivities = <ActivityData>[].obs;
  final RxBool _isLoadingUserActivities = false.obs;
  
  // 🔥 新增：公开的getter用于访问加载状态
  bool get isLoadingUserActivities => _isLoadingUserActivities.value;
  
  // 🔥 新增：公开的方法用于刷新活动数据
  Future<void> refreshUserActivities() async {
    if (isCurrentUser.value) {
      await _loadCurrentUserActivities();
    }
  }
  
  // PageController用于轮播图
  late final PageController pageController;

  @override
  void onInit() {
    super.onInit();
    
    developer.log('UserInfoController初始化');
    
    // 初始化PageController
    pageController = PageController(initialPage: 0);
    
    // 检查是否传递了其他用户信息
    if (Get.arguments != null) {
      if (Get.arguments is ChatUser) {
        // 旧的ChatUser格式
        otherUser = Get.arguments as ChatUser;
        _checkIfCurrentUser();
        developer.log('显示用户信息: ${otherUser!.name}, 是否为当前用户: ${isCurrentUser.value}');
      } else if (Get.arguments is Map<String, dynamic>) {
        // 新的API数据格式
        otherUserDetails = Get.arguments as Map<String, dynamic>;
        _checkIfCurrentUserFromDetails();
        developer.log('显示API用户信息: ${otherUserDetails!['username']}, 是否为当前用户: ${isCurrentUser.value}');
      } else {
        // 其他格式，显示当前用户
        isCurrentUser.value = true;
        developer.log('未知参数格式，显示当前登录用户信息');
      }
    } else {
      // 没有传递用户，显示当前登录用户
      isCurrentUser.value = true;
      developer.log('显示当前登录用户信息');
    }
    
    // 加载轮播图数据
    _loadCarouselImages();
    
    // 🔥 修复：调试活动进行时数据和加载活动数据
    if (isCurrentUser.value) {
      // 🔥 如果是当前用户，加载用户自己的活动数据（无论是否有otherUserDetails）
      _loadCurrentUserActivities();
    } else if (otherUserDetails != null) {
      // 🔥 如果是其他用户，调试现有活动数据并检查好友关系
      debugOngoingActivities();
      // 检查好友关系
      _checkFriendRelationship();
    }
    
    // 打印当前用户信息（调试用）
    if (userService.isLoggedIn && userService.currentUser != null) {
      developer.log('当前用户: ${userService.currentUser!.username}');
      developer.log('用户ID: ${userService.currentUser!.userid}');
      developer.log('用户头像: ${userService.currentUser!.userAvatarUrl}');
    }
  }
  
  // 🎯 检查传入的用户是否是当前登录用户
  void _checkIfCurrentUser() {
    if (otherUser != null && userService.isLoggedIn && userService.currentUser != null) {
      // 比较用户ID来判断是否是同一个用户
      final currentUserId = userService.currentUser!.userid.toString();
      final otherUserId = otherUser!.id.toString();
      
      isCurrentUser.value = currentUserId == otherUserId;
      
      developer.log('🔍 =============== 用户身份检查 ===============');
      developer.log('当前登录用户ID: $currentUserId');
      developer.log('传入用户ID: $otherUserId');
      developer.log('是否为同一用户: ${isCurrentUser.value}');
      developer.log('🔍 =============== 用户身份检查结束 ===============');
    } else {
      isCurrentUser.value = false;
      developer.log('⚠️ 无法进行用户身份检查：otherUser或currentUser为null');
    }
  }

  // 🎯 检查传入的API用户详情是否是当前登录用户
  void _checkIfCurrentUserFromDetails() {
    if (otherUserDetails != null && userService.isLoggedIn && userService.currentUser != null) {
      // 比较用户ID来判断是否是同一个用户
      final currentUserId = userService.currentUser!.userid;
      final otherUserId = otherUserDetails!['userId'];
      
      isCurrentUser.value = currentUserId == otherUserId;
      
      developer.log('🔍 =============== API用户身份检查 ===============');
      developer.log('当前登录用户ID: $currentUserId');
      developer.log('传入用户ID: $otherUserId');
      developer.log('是否为同一用户: ${isCurrentUser.value}');
      developer.log('🔍 =============== API用户身份检查结束 ===============');
    } else {
      isCurrentUser.value = false;
      developer.log('⚠️ 无法进行API用户身份检查：otherUserDetails或currentUser为null');
    }
  }
  
  // 加载轮播图数据
  void _loadCarouselImages() {
    developer.log('📸 ================ 开始加载轮播图数据 ================');
    developer.log('📱 当前用户模式: ${isCurrentUser.value ? "显示当前用户" : "显示其他用户"}');
    
    if (isCurrentUser.value && userService.currentUser != null) {
      // 显示当前用户的图片
      final user = userService.currentUser!;
      final userImgUrls = user.userImgUrls;
      
      developer.log('👤 当前用户信息:');
      developer.log('  📛 用户名: ${user.username}');
      developer.log('  🆔 用户ID: ${user.userid}');
      developer.log('  🖼️ 用户相册原始数据: $userImgUrls (类型: ${userImgUrls.runtimeType})');
      
      if (userImgUrls != null && userImgUrls.isNotEmpty) {
        developer.log('✅ 发现用户相册图片: ${userImgUrls.length}张');
        for (int i = 0; i < userImgUrls.length; i++) {
          developer.log('    🔗 图片${i + 1}: ${userImgUrls[i]}');
        }
        carouselImages.addAll(userImgUrls);
        developer.log('📋 轮播图列表已更新: ${carouselImages.length}张图片');
      } else {
        developer.log('⚠️ 用户相册为空或null，使用默认图片');
        _loadDefaultImages();
      }
    } else if (otherUserDetails != null) {
      // 显示API获取的其他用户图片
      final userImgUrls = otherUserDetails!['userImgUrls'] as List<String>?;
      
      developer.log('👤 API用户信息:');
      developer.log('  📛 用户名: ${otherUserDetails!['username']}');
      developer.log('  🆔 用户ID: ${otherUserDetails!['userId']}');
      developer.log('  🖼️ 用户相册数据: $userImgUrls');
      
      if (userImgUrls != null && userImgUrls.isNotEmpty) {
        developer.log('✅ 发现API用户相册图片: ${userImgUrls.length}张');
        for (int i = 0; i < userImgUrls.length; i++) {
          developer.log('    🔗 图片${i + 1}: ${userImgUrls[i]}');
        }
        carouselImages.addAll(userImgUrls);
        developer.log('📋 轮播图列表已更新: ${carouselImages.length}张图片');
      } else {
        developer.log('⚠️ API用户相册为空或null，使用默认图片');
        _loadDefaultImages();
      }
    } else {
      developer.log('🎲 显示其他用户或用户未登录，使用默认图片');
      _loadDefaultImages();
    }
    
    developer.log('📸 ================ 轮播图数据加载完成 ================');
  }
  
  // 🔥 加载默认图片（删除测试数据，使用系统默认头像）
  void _loadDefaultImages() {
    carouselImages.addAll([
      'http://app.playtruly.cn/system/avatar.jpg', // 使用系统默认头像作为占位图
    ]);
    developer.log('加载默认占位图片');
  }
  
  // 🔥 新增：加载当前用户的活动数据（与MyApplication2的minePublishContent对应）
  Future<void> _loadCurrentUserActivities() async {
    if (!userService.isLoggedIn || userService.currentUser == null) {
      developer.log('⚠️ 用户未登录，无法加载活动数据');
      return;
    }

    try {
      _isLoadingUserActivities.value = true;
      developer.log('🔄 =============== 开始加载当前用户活动数据 ===============');
      
      final currentUserId = userService.currentUser!.userid;
      developer.log('👤 当前用户ID: $currentUserId');

      final response = await UserApi.getUserContent(
        userId: currentUserId,
        days: 365, // 🗓️ 查询最近一年的数据
      );

      if (response.isSuccess) {
        developer.log('✅ 用户活动数据加载成功');
        developer.log('📝 总活动数量: ${response.activities.length}');
        developer.log('📝 已结束活动数量: ${response.endedActivities.length}');
        
        // 清空现有数据并添加新数据
        _currentUserActivities.clear();
        _currentUserActivities.addAll(response.activities);
        
        // 筛选出进行中的活动（与MyApplication2保持一致）
        final ongoingActivities = response.activities.where((activity) => activity.isActive).toList();
        developer.log('📊 进行中的活动数量: ${ongoingActivities.length}');
        
        // 打印活动详情
        for (int i = 0; i < ongoingActivities.length && i < 3; i++) {
          final activity = ongoingActivities[i];
          developer.log('   活动${i + 1}: ${activity.activityTitle} (状态: ${activity.activityStatus})');
          developer.log('   发布时间: ${activity.activityPublishTime}');
        }
        
      } else {
        developer.log('❌ 用户活动数据加载失败: ${response.message ?? "未知错误"}');
      }
      
      developer.log('🔍 =============== 用户活动数据加载完成 ===============');
    } catch (e) {
      developer.log('💥 加载用户活动数据异常: $e');
    } finally {
      _isLoadingUserActivities.value = false;
    }
  }
  
  // 更新当前轮播图索引
  void updateCarouselIndex(int index) {
    currentCarouselIndex.value = index;
  }
  
  // 🔥 跳转到聊天页面（参考MyApplication2架构优化）
  Future<void> navigateToChat() async {
    try {
      developer.log('🎯 准备跳转到聊天页面');
      
      // 🔥 非阻塞确保融云连接
      final rongCloudService = RongCloudService.to;
      if (!rongCloudService.isConnected.value) {
        developer.log('🔄 跳转前确保融云连接');
        rongCloudService.connectIM(); // 非阻塞连接
      }
      
      if (otherUser != null) {
        // 使用现有的ChatUser对象聊天
        developer.log('✅ 使用ChatUser对象跳转聊天: ${otherUser!.name}');
        Get.toNamed(RouteNames.messageMessageChat, arguments: otherUser);
      } else if (otherUserDetails != null) {
        // 从API数据创建ChatUser对象
        try {
          final chatUser = ChatUser(
            id: otherUserDetails!['userId'].toString(),
            name: otherUserDetails!['username'] ?? '未知用户',
            avatarUrl: otherUserDetails!['avatar'] ?? '',
          );
          
          developer.log('✅ 从API数据创建ChatUser对象: ${chatUser.name}');
          Get.toNamed(RouteNames.messageMessageChat, arguments: chatUser);
        } catch (e) {
          developer.log('❌ 创建ChatUser对象失败: $e');
          ToastUtil.error('无法创建聊天对象');
        }
      } else {
        developer.log('❌ 没有可用的用户信息');
        ToastUtil.warning('用户信息不完整，无法发起聊天');
      }
      
    } catch (e) {
      developer.log('💥 跳转到聊天页面异常: $e');
      ToastUtil.error('跳转失败，请重试');
    }
  }
  
  // 跳转到历史记录页面
  void navigateToHistory() {
    // 传递当前用户信息到历史记录页面
    if (userService.isLoggedIn && userService.currentUser != null) {
      Get.toNamed(RouteNames.myUserHistoryActivite, arguments: {
        'userId': userService.currentUser!.userid,
        'userName': userService.currentUser!.username ?? '未知用户',
      });
    } else {
      ToastUtil.warning('请先登录');
    }
  }
  
  // 检查好友关系
  void _checkFriendRelationship() async {
    if (!userService.isLoggedIn || userService.currentUser == null) {
      developer.log('⚠️ 用户未登录，无法检查好友关系');
      return;
    }

    if (isCurrentUser.value) {
      developer.log('ℹ️ 查看的是当前用户自己，无需检查好友关系');
      return;
    }

    int? targetUserId;
    if (otherUserDetails != null) {
      targetUserId = otherUserDetails!['userId'];
    } else if (otherUser != null) {
      targetUserId = int.tryParse(otherUser!.id);
    }

    if (targetUserId == null) {
      developer.log('⚠️ 无法获取目标用户ID，无法检查好友关系');
      return;
    }

    try {
      developer.log('🔍 开始检查好友关系...');
      final currentUserId = userService.currentUser!.userid;
      
      final response = await FriendApi.checkFriendRelationship(
        userId: currentUserId,
        targetUserId: targetUserId,
      );

      if (response.isSuccess && response.data != null) {
        isFriend.value = response.data!.isFriend ?? false;
        developer.log('✅ 好友关系检查完成: ${isFriend.value ? "已是好友" : "非好友关系"}');
      } else {
        // 如果检查失败，默认为非好友关系
        isFriend.value = false;
        developer.log('⚠️ 好友关系检查失败，默认为非好友: ${response.message}');
      }
    } catch (e) {
      developer.log('❌ 好友关系检查异常: $e');
      isFriend.value = false;
    }
  }

  // 添加好友
  void addFriend() async {
    if (!userService.isLoggedIn || userService.currentUser == null) {
      ToastUtil.warning('请先登录');
      return;
    }

    int? targetUserId;
    String targetUserName = '未知用户';
    
    if (otherUserDetails != null) {
      targetUserId = otherUserDetails!['userId'];
      targetUserName = otherUserDetails!['username'] ?? '未知用户';
    } else if (otherUser != null) {
      targetUserId = int.tryParse(otherUser!.id);
      targetUserName = otherUser!.name;
    }

    if (targetUserId == null) {
      ToastUtil.error('无法获取用户信息');
      return;
    }

    try {
      developer.log('🎯 开始发送好友申请...');
      final currentUserId = userService.currentUser!.userid;
      
      // 显示加载状态
      Get.dialog(
        const AlertDialog(
          content: Row(
            children: [
              CircularProgressIndicator(),
              SizedBox(width: 16),
              Text('发送好友申请中...'),
            ],
          ),
        ),
        barrierDismissible: false,
      );

      final response = await FriendApi.sendFriendRequest(
        senderId: currentUserId,
        receiverId: targetUserId,
        message: '你好，我想加你为好友',
        free: PermissionUtil.calculateAddFriendFree(), // 🎯 动态计算加好友权限（模仿MyApplication2）
      );

      // 关闭加载对话框
      Get.back();

      if (response.isSuccess) {
        // 🎯 增加加好友计数（模仿MyApplication2的逻辑）
        PermissionUtil.incrementAddFriendCount();
        
        developer.log('✅ 好友申请发送成功');
        ToastUtil.success('已向 $targetUserName 发送好友申请，请等待对方处理');
      } else {
        developer.log('❌ 好友申请发送失败: ${response.message}');
        
        // 处理特殊情况
        String message = response.message;
        if (message.contains('已经发送过好友申请') || message.contains('请等待对方处理')) {
          ToastUtil.warning(message);
        } else {
          ToastUtil.error(message);
        }
      }
    } catch (e) {
      // 关闭加载对话框（如果还开着的话）
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      
      developer.log('💥 发送好友申请异常: $e');
      ToastUtil.error('发送好友申请失败，请稍后重试');
    }
  }

  // 获取当前展示用户的信息的getter方法
  String get displayUserName {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.username ?? '未知用户';
    } else if (otherUserDetails != null) {
      return otherUserDetails!['username'] ?? '未知用户';
    } else if (otherUser != null) {
      return otherUser!.name;
    }
    return '未知用户';
  }
  
  String get displayUserId {
    if (isCurrentUser.value && userService.currentUser != null) {
      return '用户${userService.currentUser!.userid}';
    } else if (otherUserDetails != null) {
      return '用户${otherUserDetails!['userId']}';
    } else if (otherUser != null) {
      return '用户${otherUser!.id}';
    }
    return '用户未知';
  }
  
  int get displayUserFollowers {
    if (isCurrentUser.value) {
      // 🔥 对于当前用户，使用好友数量（符合MyApplication2逻辑）
      try {
        final myIndexController = Get.find<MyIndexController>();
        return myIndexController.friendCount;
      } catch (e) {
        developer.log('⚠️ 无法获取MyIndexController: $e');
        return 0;
      }
    } else if (otherUserDetails != null) {
      // 🔥 对于其他用户，使用API返回的好友数量（符合MyApplication2逻辑）
      return otherUserDetails!['friendCount'] ?? 0;
    }
    return 0;
  }
  
  int get displayUserLikes {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userLikes ?? 0;
    } else if (otherUserDetails != null) {
      return otherUserDetails!['userLikes'] ?? 0;
    }
    return 0; // 其他用户暂时返回0
  }
  

  

  
  String get displayUserFrequentPlaces {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userFrequentPlaces ?? '未知';
    } else if (otherUserDetails != null) {
      return otherUserDetails!['userFrequentPlaces'] ?? '未知';
    }
    return '未知'; // 其他用户暂时返回未知
  }
  
  String get displayUserAvatar {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userAvatarUrl ?? 'http://app.playtruly.cn/system/avatar.jpg';
    } else if (otherUserDetails != null) {
      return otherUserDetails!['avatar'] ?? 'http://app.playtruly.cn/system/avatar.jpg';
    } else if (otherUser != null) {
      return otherUser!.avatarUrl;
    }
    return 'http://app.playtruly.cn/system/avatar.jpg'; // 🔥 使用系统默认头像（删除测试数据）
  }
  
  // 🎯 根据积分计算等级（按照新的积分等级规定）
  int calculateLevelFromPoints(int points) {
    if (points >= 1200) {
      return 4; // 一言九鼎
    } else if (points >= 600) {
      return 3; // 真神
    } else if (points >= 300) {
      return 2; // 创造者
    } else if (points >= 100) {
      return 1; // 守护者
    } else {
      return 0; // 追随者
    }
  }
  
  // 🎯 根据积分返回等级名称
  String getLevelNameFromPoints(int points) {
    final level = calculateLevelFromPoints(points);
    switch (level) {
      case 0:
        return '追随者';
      case 1:
        return '守护者';
      case 2:
        return '创造者';
      case 3:
        return '真神';
      case 4:
        return '一言九鼎';
      default:
        return '追随者';
    }
  }
  
  // 🎯 获取当前显示用户的积分
  int get displayUserPoints {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userPoints ?? 0;
    } else if (otherUserDetails != null) {
      return otherUserDetails!['userPoints'] ?? 0;
    }
    return 0;
  }
  
  // 🎯 根据积分计算并返回等级数字
  int get displayUserLevel {
    final points = displayUserPoints;
    return calculateLevelFromPoints(points);
  }
  
  // 🎯 根据积分计算并返回等级名称
  String get displayUserLevelName {
    final points = displayUserPoints;
    return getLevelNameFromPoints(points);
  }
  
  // 添加新的getter方法来支持API数据
  String get displayUserSignature {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userSignature ?? '这个人很懒，什么都没留下';
    } else if (otherUserDetails != null) {
      // 🔥 修复：统一字段名，优先使用userSignature，兼容signature
      return otherUserDetails!['userSignature'] ?? otherUserDetails!['signature'] ?? '这个人很懒，什么都没留下';
    }
    return '这个人很懒，什么都没留下';
  }
  
  List<String> get displayUserTags {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userTags ?? [];
    } else if (otherUserDetails != null) {
      final tags = otherUserDetails!['userTags'];
      if (tags is List) {
        return List<String>.from(tags);
      }
    }
    return [];
  }
  
  List<String> get displayUserHobbies {
    if (isCurrentUser.value && userService.currentUser != null) {
      return userService.currentUser!.userHobbies ?? [];
    } else if (otherUserDetails != null) {
      final hobbies = otherUserDetails!['userHobbies'];
      if (hobbies is List) {
        return List<String>.from(hobbies);
      }
    }
    return [];
  }
  
  // 获取进行中的活动列表（与MyApplication2保持一致）
  List<ActivityData> get displayOngoingActivities {
    if (isCurrentUser.value && userService.currentUser != null) {
      // 🔥 修复：当前用户查看自己的信息，返回从API获取的活动数据
      final ongoingActivities = _currentUserActivities.where((activity) => activity.isActive).toList();
      developer.log('🔄 当前用户活动数据 - 总数: ${_currentUserActivities.length}, 进行中: ${ongoingActivities.length}');
      return ongoingActivities;
    } else if (otherUserDetails != null && otherUserDetails!['activities'] != null) {
      try {
        final activitiesData = otherUserDetails!['activities'];
        if (activitiesData is List<ActivityData>) {
          // 已经是ActivityData类型的列表
          return activitiesData.where((activity) => activity.isActive).toList();
        } else if (activitiesData is List) {
          // 是List但不是ActivityData类型，尝试转换（但当前从评论页传入的是空数组）
          developer.log('⚠️ activities数据不是List<ActivityData>类型，当前为: ${activitiesData.runtimeType}');
          return [];
        }
      } catch (e) {
        developer.log('❌ 处理activities数据失败: $e');
        return [];
      }
    }
    return [];
  }
  
  // 格式化活动时间（仿照MyApplication2的timeReplace方法）
  String formatActivityTime(String publishTime) {
    try {
      // 解析时间字符串，格式如：2025-08-24T19:28:00
      final dateTime = DateTime.parse(publishTime);
      // 格式化为 YYYY-MM-DD HH:mm:ss（与MyApplication2一致）
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}';
    } catch (e) {
      developer.log('⚠️ 时间格式化失败: $e');
      return publishTime; // 返回原始时间
    }
  }
  
  // 打印活动进行时的调试信息
  void debugOngoingActivities() {
    try {
      final activities = displayOngoingActivities;
      developer.log('📋 =============== 活动进行时调试信息 ===============');
      developer.log('🎯 进行中的活动数量: ${activities.length}');
      
      for (int i = 0; i < activities.length; i++) {
        final activity = activities[i];
        developer.log('📝 活动${i + 1}:');
        developer.log('   📛 标题: ${activity.activityTitle}');
        developer.log('   ⏰ 发布时间: ${activity.activityPublishTime}');
        developer.log('   📅 格式化时间: ${formatActivityTime(activity.activityPublishTime)}');
        developer.log('   🎯 状态: ${activity.activityStatus}');
        developer.log('   👥 参与人数: ${activity.activityCurrentParticipants}/${activity.activityMaxParticipants}');
      }
      developer.log('📋 =============== 活动进行时调试信息结束 ===============');
    } catch (e) {
      developer.log('❌ 调试活动信息时发生错误: $e');
      developer.log('📋 =============== 活动进行时调试信息结束（错误） ===============');
    }
  }
  
  // 申请加入活动（使用真实API）
  void joinActivity(ActivityData activity) async {
    developer.log('🎯 用户尝试加入活动: ${activity.activityTitle} (活动ID: ${activity.activityId})');
    
    // 检查用户是否登录
    if (!userService.isLoggedIn || userService.currentUser == null) {
      ToastUtil.warning('请先登录');
      return;
    }

    // 检查是否试图加入自己的活动
    final currentUserId = userService.currentUser!.userid;
    if (activity.publisherId == currentUserId) {
      ToastUtil.info('您无法申请加入自己发布的活动');
      return;
    }
    
    // 显示美化的确认对话框
    final result = await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  color: const Color(0xFFD94841).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.event_available,
                  color: Color(0xFFD94841),
                  size: 30,
                ),
              ),
              const SizedBox(height: 16),
              
              // 标题
              const Text(
                '申请加入活动',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 12),
              
              // 活动信息
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '活动名称：${activity.activityTitle}',
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '发布时间：${formatActivityTime(activity.activityPublishTime)}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),
              
              // 按钮组
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(result: false),
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                          side: BorderSide(color: Colors.grey[300]!),
                        ),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () => Get.back(result: true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFD94841),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        elevation: 0,
                      ),
                      child: const Text(
                        '确定申请',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );

    if (result != true) return;

    try {
      developer.log('🎯 开始调用加入活动API...');
      
      // 显示加载状态
      Get.dialog(
        const AlertDialog(
          content: Row(
            children: [
              CircularProgressIndicator(),
              SizedBox(width: 16),
              Text('正在申请加入活动...'),
            ],
          ),
        ),
        barrierDismissible: false,
      );

      final currentUser = userService.currentUser!;
      
      // 调用加入活动API（使用AES加密）
      final response = await ActivityApi.joinActivity(
        activityId: activity.activityId,
        userId: currentUser.userid,
        userNickname: currentUser.username ?? '未知用户',
        userAvatarUrl: currentUser.userAvatarUrl,
        userSignature: currentUser.userSignature,
        userTags: currentUser.userTags,
        userPoints: currentUser.userPoints,
        participantStatus: '待审核', // 默认状态
        extraData: null, // 可以添加额外数据
      );

      // 关闭加载对话框
      Get.back();

      if (response.isSuccess) {
        developer.log('✅ 加入活动成功: ${response.message}');
        ToastUtil.success(response.message);
        
        // 🔥 发送融云活动申请推送消息
        try {
          await ActivityApi.sendRongCloudActivityRequestPush(
            activityId: activity.activityId,
            activityTitle: activity.activityTitle,
            activityPublisherId: activity.publisherId,
            applicantUserId: currentUser.userid,
            applicantUserName: currentUser.username ?? '未知用户',
          );
          developer.log('✅ 活动申请融云推送发送完成');
        } catch (pushError) {
          developer.log('⚠️ 活动申请融云推送发送失败: $pushError');
          // 推送失败不影响主流程
        }
      } else {
        developer.log('❌ 加入活动失败: ${response.message}');
        // 对于重复参加等特殊情况使用ToastUtil
        if (response.message.contains('重复参加') || response.message.contains('已参加')) {
          ToastUtil.warning(response.message);
        } else {
          ToastUtil.error(response.message);
        }
      }

    } catch (e) {
      // 关闭加载对话框（如果还开着的话）
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      
      developer.log('💥 加入活动异常: $e');
      ToastUtil.error('申请加入活动失败，请稍后重试');
    }
  }

  @override
  void onClose() {
    pageController.dispose();
    super.onClose();
  }
}
